package com.qing.spark.beans

import java.text.SimpleDateFormat

/**
  * Created by wuliao on 2018/3/13.
  */
class Message(var timestamp: String, var message: String, var host: String) extends Serializable {

  private var version = ""
  private var proxyIp = ""
  private var srcIp = ""
  private var outIp = ""
  private var time = 0L
  private var second = 0L
  private var minute = 0L
  private var hour = 0L
  private var day = 0
  private var sampling = 0

  def getSecond: Long = second

  def getMinute: Long = minute

  def getHour: Long = hour

  def getDay: Int = day

  private var inPort = 0
  private var outPort = 0

  def getProxyIp: String = proxyIp

  def getSrcIp: String = srcIp

  def getOutIp: String = outIp

  def getTime: Long = time

  def getInPort: Int = inPort

  def getOutPort: Int = outPort

  def getPacketSize: Int = packetSize

  def getDatagramSize: Int = datagramSize

  def getSampling: Int = sampling

  private var packetSize = 0
  private var datagramSize = 0

  def getMessage: String = message

  def getSize: Int = {
    if (isEmpty(message)) return 0
    val args = message.split(",")
    if (args(0) == "FLOW") return args(args.length - 2).toInt
    0
  }

  def parseTime() {
    if (isEmpty(timestamp)) return
    val sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

    try {
      val dt = sdf.parse(timestamp)
      time = dt.getTime
      second = (time / 1000).toLong
      minute = (second / 60).toLong
      hour = (minute / 60).toLong
      day = (hour / 24).toInt
    } catch {
      case e: Exception => {
        e.printStackTrace()
      }
    }
  }

  def parseMessage() {
    val msg = getMessage
    if (!isEmpty(msg)) {
      val args = msg.split(",")
      if (args(0) == "FLOW") {
        proxyIp = args(1)
        inPort = args(2).toInt
        outPort = args(3).toInt
        srcIp = args(9)
        outIp = args(10)
        packetSize = args(17).toInt
        datagramSize = args(18).toInt
        sampling = args(19).toInt
      }
      else if (args(0) == "CNTR") proxyIp = args(1)
    }
  }

  def parse(): Message = {
    parseTime()
    parseMessage()
    this
  }

  def setMessage(message: String) {
    this.message = message
  }

  def getVersion: String = version

  def setVersion(version: String) {
    this.version = version
  }

  def getTimestamp: String = timestamp

  def setTimestamp(timestamp: String) {
    this.timestamp = timestamp
  }

  def getHost: String = host


  def isEmpty(s: CharSequence): Boolean = {
    if (s == null) return true
    s.length == 0
  }
}
